# 路径总和II： https://leetcode-cn.com/problems/path-sum-ii/
# 字节面试题， 上一题的变形

"""
    不需要返回True，返回所有路径符合条件的列表 [[path1], [path2]]
"""

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        rst = []
        def dfs(node, targetSum, path: list):
            if not node: return False
            path.append(node.val)
            total = targetSum - node.val
            # 如果是叶子结点，进行判断是否 和为 targetSum
            if not node.left and not node.right and total == 0: 
                # 注意！！元素都是 数值，不可变类型，直接浅拷贝就行
                t = path.copy()
                rst.append(t)

            dfs(node.left, total, path)
            dfs(node.right, total, path) 

            # 回溯时，去掉当前节点
            path.pop()
        
        dfs(root, targetSum, [])
        return rst